package com.iMusic.presentationLayer;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.iMusic.businessLogicLayer.Account;
import com.iMusic.businessLogicLayer.Cart;
import com.iMusic.businessLogicLayer.Product;
import com.iMusic.util.UserMessages;

public class AddToCart extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		Account account = (Account) session.getAttribute("Account");
		String redirection = "default.jsp";
		Cart cart = null;
		
		session.removeAttribute("Error");
		
		if (account != null) {
			cart = account.getCart();
		}
		else {
			cart = (Cart) session.getAttribute("Cart");
		}
		
		if (cart == null) {
			cart = new Cart();
		}
		
		Integer productId = Integer.parseInt(request.getParameter("ProductId"));
		try {
			cart.addToCart(account, productId, 1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		session.setAttribute("Cart", cart);
		if (account != null) {
			account.setCart(cart);
		}

		response.sendRedirect(redirection);
	}
}
